package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.entity.R;
import com.ruan.entity.Spu;
import com.ruan.query.SpuQuery;
import com.ruan.service.SpuService;
import com.ruan.mapper.SpuMapper;
import com.ruan.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.List;
import java.util.Objects;

/**
* @author 59499
* @description 针对表【spu】的数据库操作Service实现
* @createDate 2023-09-11 20:16:23
*/
@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu>
    implements SpuService{

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public R<List<Spu>> getSpuList(SpuQuery spuQuery) {
        QueryWrapper<Spu> wrapper = new QueryWrapper<>();
        if (spuQuery.getCategoryId() != null) {
            wrapper.eq("category_id", spuQuery.getCategoryId());
        }
        if (StringUtils.isNotBlank(spuQuery.getKeyWord())) {
            wrapper.like("name", spuQuery.getKeyWord());
        }
        wrapper.eq("status", 1);
        wrapper.select("id", "picture", "name", "price", "stock", "total_sales");
        List<Spu> spuList = spuMapper.selectList(wrapper);
        return new R<>(200, "查询成功", spuList);
    }

    @Override
    public R<Spu> getSpuById(Integer id) {
        Spu spu = redisCache.getCacheObject("getSpuById"+id);
        if (!(spu == null)){
            return new R<>(200,"查询成功",spu);
        }
        QueryWrapper<Spu> wrapper = new QueryWrapper<>();
        wrapper.eq("status",1);
        wrapper.eq("id",id);
        wrapper.select("id","picture","name","price","stock","total_sales");
        Spu spu1 = spuMapper.selectOne(wrapper);
        redisCache.setCacheObject("getSpuById"+id,spu1);
        return new R<>(200,"查询成功",spu1);
    }

    @Override
    public R<Void> deleteSpuById(Integer id) {
        Spu spu = spuMapper.selectById(id);
        spu.setStatus(0);
        int row = spuMapper.updateById(spu);
        if (row != 1){
            return new R<>(100,"删除失败");
        }
        redisCache.deleteObject("getSpuById"+id);
        return new R<>(200,"删除成功");
    }
}




